package com.work.tqyb.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;

import androidx.lifecycle.ViewModelProvider;

import com.work.tqyb.vm.WeatherVM;
import com.work.tqyb.base.BaseActivity;
import com.work.tqyb.databinding.ActivityCityListBinding;
import com.work.tqyb.http.response.CityListResponse;
import com.work.tqyb.ui.adapter.CityAdapter;

import java.io.InputStream;

public class CityListActivity extends BaseActivity {

    private WeatherVM vm;
    private ActivityCityListBinding binding;


    private CityAdapter adapter;

    @Override
    public void initData() {
        vm = new ViewModelProvider(this).get(WeatherVM.class);
        binding = ActivityCityListBinding.inflate(getLayoutInflater());
        adapter = new CityAdapter();
        binding.lv.setAdapter(adapter);
        setContentView(binding.getRoot());
        try {
            InputStream inputStream = getAssets().open("city.json");
            vm.getCityList(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onViewClick() {
        binding.ibnBack.setOnClickListener(v -> finish());
        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String search = binding.etSearch.getText().toString();
                vm.searchList(search);
                return true;
            }
            return false;
        });

        binding.lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CityListResponse.CityBean city = adapter.cityList.get(position);
                Intent intent = new Intent();
                intent.putExtra("city", city);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
    }

    @Override
    public void observe() {
        vm.getCityListLD().observe(this, cityBeanArrayList -> {
            adapter.cityList = cityBeanArrayList;
            adapter.notifyDataSetChanged();
        });
    }
}
